<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<form class="layui-form">
    <div class="layui-inline" style="margin-top: 10px">
        <label class="layui-form-label">用户名</label>
        <div class="layui-input-inline" style="width: 200px;">
            <input type="text" name="name" autocomplete="off" class="layui-input" id="search-username"/>
        </div>
        <button class="layui-btn" lay-submit id="search-btn" lay-filter="search-btn"><i class="layui-icon">&#xe615;</i>搜索
        </button>
    </div>
</form>
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon">&#xe654;</i>添加</button>
    <button class="layui-btn layui-btn-normal layui-btn-sm" lay-event="update"><i class="layui-icon">&#xe642;</i>修改
    </button>
    <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="delete"><i class="layui-icon">&#xe640;</i>批量删除
    </button>
</div>
</script>
<table id="user-table" lay-filter="user-table"></table>
<script type="text/html" id="user-row-bar">
<a class="layui-btn layui-btn-xs layui-btn-normal " lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
</script>
<script>
//在页面里只出现一次，作用类似document.ready
layui.use(['table', 'form'], function () {
    var table = layui.table;
    var form = layui.form;
    var layer_index;
    //第一个实例
    table.render({
        elem: '#user-table'
        , id: 'user-table'
        , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
        , height: 312
        , url: '<%=request.getContextPath()%>/user?act=table' //数据接口
        , page: true //开启分页
        , limit: 2
        , limits: [2, 4, 6, 8, 10]
        , cols: [[ //表头
            {type: 'checkbox', fixed: 'left'}
            , {field: 'id', title: 'ID', width: 80}
            , {field: 'username', title: '用户名'}
            , {
                field: 'gender', title: '性别', templet: function (d) {
                    return d.gender == 1 ? '男' : '女'
                }
            }
            , {field: 'age', title: '年龄'}
            , {field: 'mobile', title: '电话'}
            , {
                field: 'role', title: '用户类型', templet: function (d) {
                    switch (d.role) {
                        case 1:
                            return '<span class="layui-badge layui-bg-orange">管理员</span>'
                        case 2:
                            return '<span class="layui-badge layui-bg-green">经理</span>'
                        case 3:
                            return '<span class="layui-badge layui-bg-green">员工</span>'
                    }
                }
            }, {fixed: 'right', toolbar: '#user-row-bar'} //这里的toolbar值是模板元素的选择器
        ]]
    });
    //头工具栏事件
    table.on('toolbar(user-table)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;
            switch (obj.event) {
                case 'add':
                    openEditLayer(null)
                    break;
                case 'update':
                    if (data.length != 1) {
                        layer.msg("请选中1行")
                        return;
                    }
                    openEditLayer(data[0].id)
                    break;
                case 'delete':
                    if (data.length > 0) {
                        deleteRow(data)
                    }
                    break;
            }
            ;
        }
    );
    //行工具栏
    table.on('tool(user-table)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

        switch (obj.event) {
            case 'edit':
                openEditLayer(data.id)
                break;
            case 'delete':
                var ids = new Array();
                ids.push(data)
                deleteRow(ids)
        }
    })
//    $("#search-btn").click(function () {
//        table.reload('user-table', {
//            where: { //设定异步数据接口的额外参数，任意设
//                name: $("#search-username").val()
//            }
//        }); //只重载数
//    })
    function deleteRow(data){
        layer.confirm('确定要删除吗', function (index) {
            var ids = new Array();
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            $.ajax({
                url: "<%=request.getContextPath()%>/user?act=delete",
                method: "post",
                data: "ids=" + ids,
                success: function (res) {
                    table.reload('user-table', {}); //只重载
                    layer.close(index)
                }
            })
        })
    }
    function openEditLayer(id) {
        layer.open({
            type: 1,
            title: "添加用户",
            area: ['500px', '500px'],
            content: $("#user-form").html(), //这里content是一个普通的String
            success: function (layero, index) {//弹出层打开之后
                form.render()//重新渲染，否则的话单选、多选、下拉框可能失效
                if (id != null) {
                    $.ajax({
                        url: "<%=request.getContextPath()%>/user?act=info",
                        method: "post",
                        data: "id=" + id,
                        success: function (res) {
                            form.val("user-edit-form", res)
                            form.val("user-edit-form", {
                                gender: res.gender + ""
                            })
                            form.render()
                        }
                    })
                }
            }
            , btn: ['提交', '取消']
            , yes: function (index, layero) {
                layer_index = index
                $("#sbtn").click()
                <%--$.ajax({--%>
                <%--url: "<%=request.getContextPath()%>/user?act=add",--%>
                <%--method: "post",--%>
                <%--data: data.field,--%>
                <%--success: function (res) {--%>
                <%--if (res.ok) {--%>
                <%--table.reload('user-table', {}); //只重载--%>
                <%--layer.close(index)//关闭--%>
                <%--} else {--%>
                <%--layer.msg(res.msg);--%>
                <%--}--%>
                <%--}--%>
                <%--})--%>
            }
            , btn2: function (index, layero) {
                layer.close(index)//关闭
            }
        });
    }

    form.on('submit(search-btn)', function (data) {
        //  console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
        table.reload('user-table', {
            where: data.field
        }); //只重载
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
    form.on('submit(sbtn)', function (data) {
        $.ajax({
            url: "<%=request.getContextPath()%>/user?act=edit",
            method: "post",
            data: data.field,
            success: function (res) {
                if (res.ok) {
                    table.reload('user-table', {}); //只重载
                    layer.close(layer_index)//关闭
                } else {
                    layer.msg(res.msg);
                }
            }
        })
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
});
</script>
<script type="text/html" id="user-form">
<form class="layui-form" id="user-edit-form" lay-filter="user-edit-form">
    <input type="hidden" name="id">
    <div class="layui-form-item">
        <label class="layui-form-label">用户名</label>
        <div class="layui-input-inline">
            <input type="text" name="username" lay-verify="required" placeholder="请输入用户名" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">密码框</label>
        <div class="layui-input-inline">
            <input type="password" name="password" placeholder="请输入密码" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">性别</label>
        <div class="layui-input-block">
            <input type="radio" name="gender" value="1" title="男">
            <input type="radio" name="gender" value="2" title="女">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">年龄</label>
        <div class="layui-input-inline">
            <input type="text" name="age" lay-verify="required|number" placeholder="请输入年龄" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">电话</label>
        <div class="layui-input-inline">
            <input type="text" name="mobile" lay-verify="required|phone" placeholder="请输入电话" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">用户类型</label>
        <div class="layui-input-inline">
            <select name="role" lay-verify="required">
                <option value="">请选择</option>
                <option value="1">管理员</option>
                <option value="2">经理</option>
                <option value="3">员工</option>
            </select>
        </div>
    </div>
    <button lay-submit style="display: none" id="sbtn" lay-filter="sbtn"></button>
</form>
</script>
